import java.util.Random;

public class KthLargestElementInAnArray {
    public int findKthLargest1(int[] nums, int k) {
        return qSort(nums, 0, nums.length - 1, k);
    }

    public int qSor1t(int[] nums, int l, int r, int k) {

        // 划分区域
        // 随机选择基准值
        int pivot = nums[new Random().nextInt(r - l + 1) + l];
        int left = l - 1, i = l, right = r + 1;
        while(i < right) {
            if(nums[i] < pivot) {
                swap(nums, ++left, i++);
            }else if(nums[i] == pivot) {
                i++;
            }else {
                swap(nums, --right, i);
            }
        }

        qSort(nums, l, left, k);
        qSort(nums, right, r, k);

        int c = r - right + 1;
        // int b = (i - 1) - (left + 1) + 1;
        int b = i - left  + 1;
        int a = left - l + 1;
        if(c >= k) {
            return nums[right - k + 1];
        }else if(b + c >= k) {
            return pivot;
        }else {
            return nums[left - (k - b - c) + 1];
        }
    }


    public int findKthLargest(int[] nums, int k) {
        return qSort(nums, 0, nums.length - 1, k);
    }

    public int qSort(int[] nums, int l, int r, int k) {
        // 1. 随机选择基准值
        int pivot = nums[new Random().nextInt(r - l + 1) + l];

        // 2.根据基准元素, 把数组分成三部分
        int left = l - 1, i = l, right = r + 1;
        while(i < right) {
            if(nums[i] < pivot) {
                swap(nums, ++left, i++);
            }else if(nums[i] == pivot) {
                i++;
            }else {
                swap(nums, --right, i);
            }
        }

        // 分类讨论
        // 最后划分的区间为
        //  [l, left]   [left + 1, right - 1]    [right, r]
        //    a 区域         b 区域                c 区域
        //  小于pivot       等于pivot            大于pivot
        int a = left - l + 1; // a区域元素个数
        int b = right - left - 1; // b区域元素个数
        int c = r - right + 1; // c区域元素个数
        if(c >= k) {
            return qSort(nums, right, r, k);
        }else if(b + c >= k) {
            return pivot;
        }else {
            return qSort(nums, l, left, k - b - c);
        }
    }

    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
